package com.ebelter.seneo.models;


import android.content.Context;
import android.os.Message;
import android.text.TextUtils;
import com.ebelter.btcomlib.models.bluetooth.products.scale.bean.ScaleMeasureResult;
import com.ebelter.btcomlib.models.db.products.seneo.SeneoUserCurrentMeasureRecord;
import com.ebelter.btcomlib.models.db.products.seneo.SeneoUserMeasureUploadData;
import com.ebelter.btcomlib.models.db.products.seneo.SeneoUserinfos;
import com.ebelter.btcomlib.models.https.BaseJsonGenerator;
import com.ebelter.btcomlib.models.https.interfaces.HttpResponse;
import com.ebelter.btcomlib.utils.BaseHandle;
import com.ebelter.btcomlib.utils.NumUtils;
import com.ebelter.btcomlib.utils.log.LogUtils;
import com.ebelter.seneo.beans.httpresponse.OriginalParametersResponse;
import com.ebelter.seneo.contants.IUserContant;
import com.ebelter.seneo.ui.fragments.main.Trend_Fragment;
import com.ebelter.seneo.utils.BodyCompositionCriteria;
import com.ebelter.seneo.utils.SeneoUtils;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * 此工具专门负责上传数据到后台
 */

public class UploadData2ServiceUtil extends BaseHandle{
    private static final String TAG = "LoadData2Service";
    private BaseJsonGenerator mBaseJsonGenerator;



    public UploadData2ServiceUtil() {
        this.mBaseJsonGenerator = new BaseJsonGenerator();
        autoCheck();
    }

    private static final int WHAT_CHECK = 0;
    @Override
    public void handleMsg(Message msg) {
        super.handleMsg(msg);

        if (WHAT_CHECK==msg.what){
            autoCheck();
        }

    }

    private boolean isUploadDataFlag;//是否正在上传数据的标志
    private void autoCheck() {

        removeMessages(WHAT_CHECK);
        if (isUploadDataFlag){//说明正在有数据上传
            sendEmptyMessageDelayed(WHAT_CHECK,2000);
            LogUtils.i2(TAG,"正在上传数据 2秒后再次检测");
            return;
        }else {
            sendEmptyMessageDelayed(WHAT_CHECK,6000);
        }
        final SeneoUserMeasureUploadData h = SeneoDbUtils.getSeneoUserMeasureUploadData();
        if (h==null){
            LogUtils.i2(TAG,"UploadData2ServiceUtil 未检测到有上传数据");
            return;
        }
        final long userid = h.user_id;
        if (userid<=0){
            LogUtils.i2(TAG,"UploadData2ServiceUtil 检测到数据不对 userid="+userid);
            LogUtils.i2(TAG,h.toString());
            h.delete();
            return;
        }
        final long hostId = h.host_id;

        final float weight=numFatmat(h.weight);
        final float fat=numFatmat(h.fat);
        final float bmi=numFatmat(h.bmi);
        final float bmr=numFatmat(h.bmr);
        final float vf= numFatmat(h.visceralFat);//内脂等级
        final float muscleMass=numFatmat(h.muscleVolume);
        final float boneMass=numFatmat(h.boneVolume);
        final float protein=numFatmat(h.protein);
        final float waterRate=numFatmat(h.waterRate);
        final float skeletalMuscle=numFatmat(h.skeletalMuscle);
        final int bodyScore=  h.bodyScore;
        final int bodyAge= h.bodyAge;
        final float tofatWeight= h.tofatWeight;
        final float weightControl= h.weightControl;
        final int size = h.size;
        final String measureTime = h.measureTime;

        //上传测量数据到后台
        Map<String, Serializable> paramMap = new HashMap<>();
        paramMap.put("userid",userid);
        paramMap.put("weight", weight);
        paramMap.put("bmi", bmi);
        paramMap.put("bmr", bmr);
        //  paramMap.put(HttpsParameters.VISCERAL_FAT, fat);//脂肪率
        paramMap.put("adipose_rate", fat);//脂肪率
        paramMap.put("visceralFat", vf);//内脂等级
        paramMap.put("muscleQuantity", muscleMass);
        paramMap.put("boneMass", boneMass);
        paramMap.put("protein", protein);
        paramMap.put("moisture", waterRate);//水分
        paramMap.put("boneMineralContent", skeletalMuscle);//骨骼肌
        paramMap.put("bodySocre", bodyScore);
        paramMap.put("physicalAge",bodyAge);

        if (tofatWeight>0){
            paramMap.put("toFatWeight",tofatWeight);
        }
        paramMap.put("weightControl",weightControl);

        if (size>=0){
            paramMap.put("size",size);
        }


        paramMap.put("testDate", measureTime);




        isUploadDataFlag = true;
        SeneoNet.getIntance().uploadData(TAG, paramMap, new HttpResponse<OriginalParametersResponse>() {
            @Override
            public void result(boolean isRequestSuccess, String requestDes, OriginalParametersResponse originalParametersResponse,String s) {
                isUploadDataFlag = false;


                LogUtils.i(TAG,"-----缓存池数据 "+h);
                if (isRequestSuccess) {
                    if (originalParametersResponse.resultCode == 0) {
                        LogUtils.i2(TAG, "-----缓存池数据----上传成功---");
                        h.delete();
                        SeneoUtils.sendCommonEventBus(TAG, Trend_Fragment.TAG, IUserContant.ICMDS.REQUEST_TREND_DATA,"上传数据成功，重新请求趋势数据");
                       // saveCurrentMeasureData(hostId,userid,measureTime,fat,weight,waterRate,bmr,vf,muscleMass,skeletalMuscle,boneMass,bmi,protein,bodyAge,bodyScore);


                    } else {
                        LogUtils.i2(TAG, "-----缓存池数据----上传失败：" + originalParametersResponse.resultMessage);
                    }
                } else {
                    LogUtils.i2(TAG, "-----缓存池数据----网络失败");
                }

            }
        });



    }

    //private String lastUploadTime;
    public void uploadData(final Object tag, final SeneoUserinfos currentUserinfos, final ScaleMeasureResult result){
        if (tag==null||currentUserinfos.host_id<=0||currentUserinfos.user_id<=0||result==null){
            return;
        }
        final float weight=numFatmat(result.getWeight());
        final float fat=numFatmat(result.getFat());
        final float bmi=numFatmat(result.getBmi());
        final float bmr=numFatmat(result.getBmr());
        final float vf= numFatmat(result.getVisceralFat());//内脂等级
        final float muscleMass=numFatmat(result.getMuscleVolume());
        final float boneMass=numFatmat(result.getBoneVolume());
        final float protein=numFatmat(result.getProtein());
        final float waterRate=numFatmat(result.getWaterRate());
        final float skeletalMuscle=numFatmat(result.getSkeletalMuscle());
        final int bodyScore= (int) result.getBodyScore();
        final int bodyAge= (int) result.getBodyAge();
        final String measureTime = result.getMeasureTime();


        //上传测量数据到后台
        Map<String, Serializable> paramMap = new HashMap<>();
        paramMap.put("userid",currentUserinfos.user_id);
        paramMap.put("weight", weight);
        paramMap.put("bmi", bmi);
        paramMap.put("bmr", bmr);
        //  paramMap.put(HttpsParameters.VISCERAL_FAT, fat);//脂肪率
        paramMap.put("adipose_rate", fat);//脂肪率
        paramMap.put("visceralFat", vf);//内脂等级
        paramMap.put("muscleQuantity", muscleMass);
        paramMap.put("boneMass", boneMass);
        paramMap.put("protein", protein);
        paramMap.put("moisture", waterRate);//水分
        paramMap.put("boneMineralContent", skeletalMuscle);//骨骼肌
        paramMap.put("bodySocre", bodyScore);
        paramMap.put("physicalAge",bodyAge);



        float tofatWeight = -1;
        if (fat!=0){
            tofatWeight=(float) (weight-weight*fat/100.0);
            paramMap.put("toFatWeight",tofatWeight);
        }

        //final float weightControl=weight- BodyCompositionCriteria.getWeightKgByBMI(24,result.height);
        final float weightControl=result.weightControl;
        paramMap.put("weightControl",weightControl);

        int size =-1;
        if (fat!=0){
            Object[] objects = BodyCompositionCriteria.getSize(fat,currentUserinfos.getAge(),currentUserinfos.sex,result.getMuscleVolume(),currentUserinfos.height);
            if (objects!=null&&objects[0]!=null&&objects[1]!=null){

                try {
                    size=(int)objects[0];
                    if (size>=0){
                        paramMap.put("size",size);
                    }
                }catch (Exception e){
                    LogUtils.i2(TAG,"---上传数据报出异常fat="+fat+"--age="+currentUserinfos.getAge()+"--sex="+currentUserinfos.sex+"---muscleVolume="+result.getMuscleVolume()+"---height="+currentUserinfos.height);
                    e.printStackTrace();
                }

            }


        }

        paramMap.put("testDate", measureTime);

        final float tofatWeight2 = tofatWeight;
        final int size2 = size;

        LogUtils.i(TAG, "上传的参数paramMap---" + mBaseJsonGenerator.getMapRJ(paramMap));

        SeneoNet.getIntance().uploadData(tag, paramMap, new HttpResponse<OriginalParametersResponse>() {
            @Override
            public void result(boolean isRequestSuccess, String requestDes, OriginalParametersResponse originalParametersResponse,String s) {

                if (isRequestSuccess) {
                    if (originalParametersResponse.resultCode == 0) {
                        LogUtils.i(TAG, "-----上传测量数据----上传成功---");

                        SeneoUtils.sendCommonEventBus(TAG, Trend_Fragment.TAG, IUserContant.ICMDS.REQUEST_TREND_DATA,"上传数据成功，重新请求趋势数据");

                        //saveCurrentMeasureData(hostId,userid,measureTime,fat,weight,waterRate,bmr,vf,muscleMass,skeletalMuscle,boneMass,bmi,protein,bodyAge,bodyScore);

                        return;

                    } else {
                        LogUtils.i(TAG, "-----上传测量数据----上传失败：" + originalParametersResponse.resultMessage);
                    }
                } else {
                    LogUtils.i(TAG, "-----上传测量数据----网络失败");
                }
                //把上传失败的数据保存在本地
                saveSeneoUserMeasureUploadData(currentUserinfos.host_id,currentUserinfos.user_id,measureTime,fat,weight,waterRate,
                        bmr,vf,muscleMass,skeletalMuscle,boneMass,bmi,protein,bodyAge,bodyScore,tofatWeight2,weightControl,size2);
            }
        });



    }









//    //保存当前测量的数据
//    private boolean saveCurrentMeasureData(long hostId,long userId,String mesureTime,float fat,float weight,float waterRate,
//                                   float bmr,float vfl,float muscleV,float skeleV,float boneV,float bmi,
//                                   float protein,int bodyAge,int bodyScore){
//        SeneoUserCurrentMeasureRecord h = SeneoDbUtils.getSeneoUserCurrentMeasureRecord(hostId,userId);
//        boolean isSave;
//        if (h == null){
//            h = new SeneoUserCurrentMeasureRecord();
//            isSave=true;
//        }else {
//
//            long srcMesureTime = time2Long(h.measureTime);
//            long nowMesureTime = time2Long(h.measureTime);
//            if (nowMesureTime<=srcMesureTime){
//                LogUtils.i2(TAG,"保存当前测量的数据失败 因为 srcMesureTime=" + srcMesureTime+"--nowMesureTime="+nowMesureTime+"---nowMesureTime<=srcMesureTime");
//                return false;
//            }
//            isSave=false;//说明更新的意思
//
//        }
//        h.host_id=hostId;
//        h.user_id=userId;
//        h.measureTime=mesureTime;
//        h.weight=weight;
//        h.fat=fat;
//        h.waterRate=waterRate;
//        h.bmr=bmr;
//        h.visceralFat=vfl;
//        h.muscleVolume=muscleV;
//        h.skeletalMuscle=skeleV;
//        h.boneVolume=boneV;
//        h.bmi=bmi;
//        h.protein=protein;
//        h.bodyAge=bodyAge;
//        h.bodyScore=bodyScore;
//
//        if (isSave){
//           return h.save();
//        }else {
//           return h.update();
//        }
//
//    }




    //把上传失败的数据保存在上传数据库中 上次再上传 保障上传成功的意思
    private void saveSeneoUserMeasureUploadData(long hostId, long userid, String measureTime, float fat,
                                                float weight, float waterRate, float bmr, float vf, float muscleMass,
                                                float skeletalMuscle, float boneMass, float bmi, float protein,
                                                int bodyAge, int bodyScore,float tofatWeight,float weightControl,int size) {

        SeneoUserMeasureUploadData h = new SeneoUserMeasureUploadData();
        h.host_id=hostId;
        h.user_id=userid;
        h.measureTime=measureTime;
        h.weight=weight;
        h.fat=fat;
        h.waterRate=waterRate;
        h.bmr=bmr;
        h.visceralFat=vf;
        h.muscleVolume=muscleMass;
        h.skeletalMuscle=skeletalMuscle;
        h.boneVolume=boneMass;
        h.bmi=bmi;
        h.protein=protein;
        h.bodyAge=bodyAge;
        h.bodyScore=bodyScore;
        h.tofatWeight=tofatWeight;
        h.weightControl=weightControl;
        h.size=size;
        h.save();

    }
















    private float numFatmat(float num){
        return NumUtils.numBaoLiuWei1(num);
    }

    private long time2Long(String dateStr){// String dateStr = "2018-05-24 12:00:00";
        if (TextUtils.isEmpty(dateStr)){
            return 0;
        }
        long longDate;
        try {
            longDate = Long.valueOf(dateStr.replaceAll("[-\\s:]",""));
        }catch (Exception e){
            e.printStackTrace();
            longDate=0;
        }
        return longDate;
    }

}
